package com.crazy.support;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import com.crazy.dao.sys.impl.MyBaseDao;

/**
 * 自定义JPA存储工厂Bean。
 * 
 * @author zhangvv
 */
public class MyJpaRepositoryFactoryBean<T extends JpaRepository<Object, Serializable>>
		extends JpaRepositoryFactoryBean<T, Object, Serializable> {
	@Override
	protected RepositoryFactorySupport createRepositoryFactory(
			EntityManager entityManager) {
		return new MyJpaRepositoryFactory(entityManager);
	}

	class MyJpaRepositoryFactory extends JpaRepositoryFactory {

		public MyJpaRepositoryFactory(EntityManager entityManager) {
			super(entityManager);
		}

		@Override
		protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
			return MyBaseDao.class;
		}

		@SuppressWarnings({ "unchecked", "rawtypes", "hiding" })
		@Override
		protected <T, ID extends Serializable> SimpleJpaRepository<T, ID> getTargetRepository(
				RepositoryMetadata metadata, EntityManager entityManager) {
			Class<T> domainClass = (Class<T>) metadata.getDomainType();
			return new MyBaseDao(domainClass, entityManager);
		}
	}
}
